<?php

namespace app\admin\model\template;

use app\admin\model\User;
use think\Model;

/**
 * 模板订单类
 */
class Order extends Model
{

    // 定义关联的数据表名称
    protected $name = 'order';
    // 开启自动时间戳字段
    protected $autoWriteTimestamp = 'integer';
    // 定义时间戳字段名
    protected $createTime = 'createtime';
    protected $updateTime = 'updatetime';
    protected $deleteTime = false;
    protected $append = [
        'factors_array',
    ];

    public function getPayStateAttr($value)
    {
        $data = [0 => '待付款', 1 => '已完成', 2 => '已取消'];
        return $data[$value];
    }

    public function getTypeAttr($value)
    {
        $data = [1 => '核算模板', 2 => '服务', 3 => '模板分成'];
        return $data[$value];
    }

    public function getCarbonAccountPriceAttr($value, $data)
    {
        return $data['type'] == 1 ? $data['price'] : $value;
    }

    public function getProductNameAttr($value, $data)
    {
        if (isset($data['type']) && $data['type'] == 2) return '产品碳足迹核算服务';
        return $value;
    }

    public function getSnAttr($value, $data)
    {
        if (isset($data['type']) && $data['type'] == 2) return null;
        return $value;
    }

    public function getEndTime($value, $createtime)
    {
        return $value == 0 ? $createtime + 900 : null;
    }

    public function getFactorsAttr($value)
    {
        if (!empty($value)) {
            $array = json_decode($value, true);
            foreach ($array as &$v) {
                $v['type'] = '碳排放因子&数据库';
            }
            unset($v);
            return $array;
        }
        return [];
    }

    public function getFactorsArrayAttr($value, $data)
    {
        if (!empty($data['factors'])) {
            $array = json_decode($data['factors'], true);
            foreach ($array as &$v) {
                $v['type'] = '碳排放因子&数据库';
            }
            $array = array_column($array, null, 'id');
            unset($v);
            return $array;
        }
        return [];
    }


    public function user()
    {
        return $this->belongsTo(User::class, 'user_id', 'id');
    }

    public function template()
    {
        return $this->belongsTo(Template::class, 'template_id', 'id');
    }

    public function orderCommissionRecord()
    {
        return $this->hasMany(OrderCommissionRecord::class, 'order_id', 'id');
    }

    public function getPaytimeTextAttr($value, $data)
    {
        $value = $value ? $value : (isset($data['paytime']) ? $data['paytime'] : '');
        return is_numeric($value) ? date("Y-m-d H:i:s", $value) : $value;
    }

    protected function setPaytimeAttr($value)
    {
        return $value === '' ? null : ($value && !is_numeric($value) ? strtotime($value) : $value);
    }


}